/**
 * 
 */
package com.effectivsocial.view.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.effectivsocial.domain.Link;
import com.effectivsocial.domain.LinkGroup;
import com.effectivsocial.domain.ViewDefinition;
import com.effectivsocial.service.api.ViewDefinitionService;

/**
 * @author Dhrubo
 * 
 */
@Slf4j
public class NavingationDetailPopulatingInterceptor extends
		HandlerInterceptorAdapter {

	private final String excludeExtensions[] = { ".css", ".js", ".gif", ".jpg",
			".png" };

	@Inject
	private ViewDefinitionService viewDefinitionService;

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		String pathInfo = request.getPathInfo();

		log.info("## PathInfo = {}", pathInfo);

		if (isExcludedUrl(pathInfo)) {
			log.info("## View Name = {}", modelAndView.getViewName());
			log.info("## Processing URL  = {}", pathInfo);

			populateAndPushNavigation(modelAndView);
		}

	}

	private void populateAndPushNavigation(ModelAndView modelAndView) {
		String viewName = modelAndView.getViewName();

		ViewDefinition viewDefinition = viewDefinitionService
				.findByName(viewName);

		if (viewDefinition != null) {

			log.info("## Retrieved view Definition  = {}", viewDefinition);

			List<LinkGroup> linkGroups = viewDefinition.getLinkGroups();

			
			List<LinkGroup> topNavBar = new ArrayList<LinkGroup>();
			List<LinkGroup> leftNavBar = new ArrayList<LinkGroup>();

			List<Link> leftNavLinks = new ArrayList<Link>();

			for (LinkGroup linkGroup : linkGroups) {

				if (StringUtil.equals(linkGroup.getPosition(), "topnav")) {
					
					log.info("Link Group = {}", linkGroup.getName());
					log.info("Associated links = {}", linkGroup.getLinks().size());
					
					topNavBar.add(linkGroup);
				} else if (StringUtil
						.equals(linkGroup.getPosition(), "leftnav")) {
					leftNavBar.add(linkGroup);

					Link headerLink = new Link();
					headerLink.setName(linkGroup.getName());
					headerLink.setLabelKey(linkGroup.getLabelKey());
					headerLink.setHeader(true);

					leftNavLinks.add(headerLink);
					leftNavLinks.addAll(linkGroup.getLinks());

				}

			}
			
			modelAndView.addObject("topNavBar", topNavBar);
			modelAndView.addObject("leftNavLinks", leftNavLinks);
		}

	}

	private boolean isExcludedUrl(String pathInfo) {

		if (StringUtil.endsWithOneIgnoreCase(pathInfo, excludeExtensions) != -1) {
			return false;
		} else {
			return true;
		}
	}

}
